package br.rfpm.web;

import java.security.NoSuchAlgorithmException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import br.rfpm.dominio.Usuario;
import br.rfpm.dominio.service.UsuarioService;
import br.rfpm.util.Mensagem;
import br.rfpm.web.util.MD5;

@Controller
@RequestMapping(value = "usuario")
public class UsuarioController {

	@Autowired
	private UsuarioService usuarioService;
	
	private Usuario novo;
	
	@RequestMapping(method = RequestMethod.GET)
	public String index() {
		return "redirect:/usuario/novo";
	}
	
	@RequestMapping(value = "novo", method = RequestMethod.GET)
	public String setUpForm(Model model) {
		model.addAttribute(Mensagem.INFOMACAO, "Cadastro de novo usuário");
		return "/usuario/novo";
	}

	@RequestMapping(value = "/novo", method = RequestMethod.POST)
	public String cadastrar(Model model) {

		try {
			novo.setCredentials(MD5.criptografar(novo.getCredentials().toString()));
			this.usuarioService.inserir(novo);
			model.addAttribute(Mensagem.SUCESSO, "Usuário Cadastrado com sucesso !");
		} catch (NoSuchAlgorithmException e) {
			model.addAttribute(Mensagem.ERRO, e.getMessage());
		}

		return index();
	}

	public Usuario getNovo() {
		return novo;
	}

	public void setNovo(Usuario novo) {
		this.novo = novo;
	}
	
}
